package com.itheima.dubbo.api;

import com.itheima.domain.mongo.*;
import com.itheima.domain.vo.PageResult;
import com.itheima.dubbo.util.IdSequence;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 阿鹏
 * @date 2021/1/28 14:12
 */
@Service
public class PublishApiImpl implements PublishApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdSequence idSequence;

    @Override
    public String save(Publish publish) {
        //1. 把动态存储到动态表publish里
        publish.setId(ObjectId.get());
        publish.setPid(idSequence.getNextId("quanzi_publish"));
        publish.setUserId(publish.getUserId());
        publish.setCreated(System.currentTimeMillis());
        mongoTemplate.save(publish);

        //2. 把动态存储到当前用户的相册表quanzi_album_用户id
        Album album = new Album();
        album.setId(ObjectId.get());
        album.setCreated(System.currentTimeMillis());
        album.setPublishId(publish.getId());
        mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

        //3. 把动态插入到当前用户好友的时间线里quanzi_timeline_好友id
        List<Friend> friendList = mongoTemplate.find(Query.query(Criteria.where("userId").is(publish.getUserId())), Friend.class);
        for (Friend friend : friendList) {
            TimeLine timeLine = new TimeLine();
            timeLine.setId(ObjectId.get());
            timeLine.setPublishId(publish.getId());
            timeLine.setUserId(publish.getUserId());
            timeLine.setCreated(System.currentTimeMillis());

            mongoTemplate.save(timeLine, "quanzi_time_line_" + friend.getFriendId());
        }
        return publish.getId().toHexString();
    }

    @Override
    public Publish findById(String publishId) {
        System.out.println(new ObjectId(publishId));
        Publish publish = mongoTemplate.findById(new ObjectId(publishId), Publish.class);
        return publish;
    }

    @Override
    public PageResult<Publish> findPublishList(int page, int pagesize, Long uid, Integer state) {
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page - 1, pagesize));
        if (uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if (state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        List<Publish> publishes = mongoTemplate.find(query, Publish.class);
        long count = mongoTemplate.count(query, Publish.class);
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int) count, pagesize, pages, page, publishes);
    }

    @Override
    public void updateState(Publish publish) {
        Query query = new Query(Criteria.where("id").is(publish.getId()));
        Update update = new Update().set("state", publish.getState());
        mongoTemplate.updateFirst(query, update, Publish.class);
    }

    @Override
    public PageResult<Publish> findAlbumList(int page, int pagesize, long userId) {
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page - 1, pagesize));
        // 查询当前用户下的相册列表
        List<Album> albumList = mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        long count = mongoTemplate.count(query, Album.class, "quanzi_album_" + userId);

        List<Publish> publishList = new ArrayList<>();
        for (Album album : albumList) {
            Publish publish = mongoTemplate.findById(album.getPublishId(), Publish.class);
            publishList.add(publish);
        }

        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int)count, pagesize, pages, page, publishList);
    }

    @Override
    public PageResult<Publish> findByTimeline(int page, int pagesize, long userId) {
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page - 1, pagesize));
        List<TimeLine> timeLineList = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);

        List<Publish> publishList = new ArrayList<>(timeLineList.size());
        for (TimeLine timeLine : timeLineList) {
            ObjectId publishId = timeLine.getPublishId();
            Publish publish = mongoTemplate.findById(publishId, Publish.class);
            publishList.add(publish);
        }

        int count = (int) mongoTemplate.count(query, TimeLine.class, "quanzi_time_line_" + userId);
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>(count,pagesize,page,page,publishList);
    }

    @Override
    public PageResult<Publish> findByRecommend(int page, int pagesize, long userId) {
        Query query = new Query(Criteria.where("userId").is(userId).and("publishId").ne(null))
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1, pagesize));
        List<RecommendQuanzi> quanziList = mongoTemplate.find(query, RecommendQuanzi.class);
        long count = mongoTemplate.count(query, RecommendQuanzi.class);

        List<Publish> publishList = new ArrayList<>();
        for (RecommendQuanzi quanzi : quanziList) {
            ObjectId publishId = quanzi.getPublishId();
            Publish publish = mongoTemplate.findById(publishId, Publish.class);
            publishList.add(publish);
        }

        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int) count, pages, pages, page, publishList);
    }

    @Override
    public List<Publish> findByPidList(List<Long> pidList) {
        Query query = new Query(Criteria.where("pid").in(pidList));
        return mongoTemplate.find(query, Publish.class);
    }

    @Override
    public void removePublishByPid(String pid) {
        Query query = new Query(Criteria.where("id").is(new ObjectId(pid)));
        mongoTemplate.remove(query, Publish.class);
    }

    @Override
    public void removeAlbumPublish(Long userId, String pid) {
        Query query = new Query(Criteria.where("publishId").is(new ObjectId(pid)));
        mongoTemplate.remove(query, Album.class, "quanzi_album_" + userId);
    }
}
